<!--
 * @Descripttion: 生态适宜指导弹出框
-->
<template>
  <div class="page-modal" 
    v-loading.fullscreen.lock="fullscreenLoading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
    :element-loading-text="loadingText">
    <lark-drawer class="eco-suitable-task-drawer" ref="workCard" title="作业面板" direction="left" width="26vw" height="auto">
      <div class="eco-suitable-main">
        <el-tabs v-model="activeTab" @tab-click="tabClick">
          <el-tab-pane label="自由绘制" name="0">
            <div class="draw-info">依托本底指数，对一片区域进行生态修复分类切割，生成多个生态适宜区域，针对每个适宜区域给出生态修复指导方案；实现区域内“宜林则林、宜草则草、宜灌则灌”。</div>
            <div class="draw-area-button-container">
              <el-button class="draw-btn" type="primary" size="small" @click="drawHandler">绘制区域</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="作业任务" name="1">
            <div class="project-task-root" v-if="addTaskHidden">
              <div class="task-header">
                <el-input class="ipt" v-model="searchValue" size="small" placeholder="输入名称进行查询"></el-input>
                <el-button class="search" size="small" type="primary" icon="el-icon-search" @click="queryWorkTaskByName">查询</el-button>
                <el-button class="add" size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
              </div>
              <div class="task-content">
                <template v-if="tableData.length > 0">
                  <div class="task-item"  v-for="(item,key) in tableData" :key="key">
                    <div class="left">
                      <p>任务名称：{{item.name}}</p>
                      <p>创建时间：{{item.createTime.split(" ")[0]}}</p>
                    </div>
                    <div class="right">
                      <el-button style="margin-right:12px" type="text" icon="el-icon-location-outline" @click="locationHandler(item)">定位</el-button>
                      <el-popconfirm title="确定删除这条任务吗？" @confirm="deleteClickHandler(item)">
                        <el-button slot="reference" type="text" icon="el-icon-delete">删除</el-button>
                      </el-popconfirm>
                    </div>
                  </div>
                </template>
                <div class="empty-box" v-else>
                  <div>
                    <p class="el-icon-box" style="font-size:60px"></p>
                    <p>暂无数据</p>
                  </div>
                </div>
              </div>
            </div>
            <div class="add-task-wrapper" v-else>
              <el-form ref="addForm" :model="addForm" label-width="80px" class="add-task" :rules="rules">
                <el-form-item label="任务名称" prop="name">
                  <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="绘制区域">
                  <el-button type="primary" size="small" @click="drawHandler">绘制区域</el-button>
                </el-form-item>
                <el-form-item label="上传文件">
                  <el-upload class="upload-shp" :action="uploadImgUrl" :on-success="handleUploadSuccess" :headers="headers" :on-error="handleUploadError" :before-upload="handleBeforeUpload" :show-file-list="false" accept="application/x-zip-compressed, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
                    <el-button size="small" type="primary">选取文件</el-button>
                    <div slot="tip" class="el-upload__tip">
                      <span class="tip-info">
                        上传文件支持shp压缩文件(zip格式)，
                        <el-tooltip effect="dark" content="点击可下载excel模板" placement="top">
                          <a class="execl" style="color: #08651a" href="/ExeclTemp.xlsx">excel文件格式</a>
                        </el-tooltip>
                      </span>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="任务描述">
                  <el-input type="textarea" v-model="addForm.description"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">确定</el-button>
                  <el-button @click="() => (addTaskHidden = true)">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </lark-drawer>
    <lark-drawer v-if="baseData" class="eco-suitable-area-drawer" ref="areaDrawer" :title="title" direction="right" width="30vw" height="auto">
      <div class="eco-suitable-main">
        <div class="header" style="background: rgba(8,110,26,0.1);">
          <div class="tit">
            <h3>作业区域基本信息</h3>
            <el-tooltip class="item" effect="dark" content="导出作业区域基本信息" placement="left">
              <div class="icon-download" @click="downloadBaseData"></div>
            </el-tooltip>
          </div>
          <div class="area">
            <i class="icon-area"></i>
            总面积 : 
            <span v-if="baseData.mj.split('.')[0].length > 5">{{ (baseData.mj/10000).toFixed(2) }}公顷</span>
            <span v-else>{{ baseData.mj }}平方米</span>
          </div>
          <div class="lon-lat">
            <span>
              <i class="icon-location"></i>
              中心点经度:{{ baseData.jd }}
            </span>
            <span>
              <i class="icon-location"></i>
              中心点纬度:{{ baseData.wd }}
            </span>
          </div>
          <div class="location">
            <i class="icon-city"></i>
            {{ baseData.xzqmc }}
          </div>
          <div class="eco-num">
            <i class="el-icon-s-flag"></i>
            生态划片区数量 : {{ baseData.sl }}
          </div>
        </div>
        <div class="header border" style="padding-left: 30px" v-if="result.selected && selectBaseData">
          <div class="tit">
            <h3>切片区域基本信息</h3>
            <el-tooltip class="item" effect="dark" :content="`导出${title}方案`" placement="left">
              <div class="icon-download" @click="downloadProgramme"></div>
            </el-tooltip>
          </div>
          <div class="area">
            <i class="icon-area"></i>
            选定区域面积 : 
            <span v-if="selectBaseData.mj.split('.')[0].length > 5">{{ (selectBaseData.mj/10000).toFixed(2) }}公顷</span>
            <span v-else>{{ selectBaseData.mj }}平方米</span>
          </div>
          <div class="lon-lat">
            <span>
              <i class="icon-location"></i>
              中心点经度:{{ baseData.jd }}
            </span>
            <span>
              <i class="icon-location"></i>
              中心点纬度:{{ baseData.wd }}
            </span>
          </div>
          <div class="eco-num">
            <i class="el-icon-s-flag"></i>
            生态整体评分 : {{ selectBaseData.pf }}
          </div>
        </div>
        <div class="guidance-plan" v-if="result.selected && programme.length > 0">
          <div class="tit" style="padding: 0 14px">
            <h3>{{ `${title}方案` }}</h3>
          </div>
          <div class="plan-body">
            <div class="con" v-for="(item, key) in programme" :key="key">
              <h4>{{ item.zzlx }}</h4>
              <p>
                <span>方案描述：{{ item.fams }}</span>
              </p>
              <div class="score">{{ item.pf }}分</div>
            </div>
          </div>
        </div>
      </div>
    </lark-drawer>
  </div>
</template>
<script>
import common from "./common";
import { getToken } from "@/utils/auth";
import XLSX from "xlsx";
import GeometryUtils from "@/utils/yc/GeometryUtils";
import {
  addWorkTask,
  delWorkTask,
  editWorkTask,
  queryWorkTaskByName
} from "@/api/eco/workTask";
export default {
  name: "SuitableModal",
  props: {
    // 结果集
    result: {
      type: Object,
      default () {
        return null;
      }
    },
    // 标题
    title: {
      type: String,
      default: "生态适宜指导"
    },
    // 类型
    type: {
      type: String,
      default: "3"
    },
    // 类型
    planType: {
      type: String,
      default: "8"
    }
  },
  data () {
    return {
      // 加载状态
      fullscreenLoading:false,
      // 加载文字
      loadingText: '正在下载中，请耐心等待......',
      // 当前选项卡
      activeTab: "0",
      // 搜索内容
      searchValue: "",
      // 表格数据
      tableData: [],
      // 当前页
      currentPage: 1,
      // 新增任务表单
      addForm: {
        name: "",
        description: "",
        ecoWorkTasks: [] //作业图形
      },
      // 文件上传列表
      fileList: [],
      // 新增任务窗口显示隐藏
      addTaskHidden: true,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/shap/toJson", // 上传的zip服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      zipData: {},
      // 划片数据
      baseData: null,
      // 选定区域数据
      selectBaseData: null,
      // 方案
      programme: [],
      rules: {
        name: [{ required: true, message: "请输入任务名称", trigger: "blur" }]
      }
    };
  },
  mixins: [common],
  watch: {
    // 结果集
    result: {
      deep: true,
      handler (newV) {
        if (newV === undefined || newV === null) return;
        this.baseData = newV.baseData;
        if (newV.selected) {
          this.selectBaseData = newV.selected.baseData;
          this.programme = newV.selected.zdfa;
        }else{
          this.selectBaseData = null;
          this.programme = [];
        }
        if (this.$refs.areaDrawer) this.$refs.areaDrawer.showState = true;
      }
    }
  },
  methods: {
    // 绘制或者上传
    radioGroupChange(){
      this.addForm.ecoWorkTasks = []
    },
    // 绘制区域
    drawHandler () {
      this.$emit("drawPolygonHandler");
    },
    // 基础信息pdf下载
    downloadBaseData () {
      const data = JSON.parse(JSON.stringify(this.result));
      data.type = this.type;
      this.downloadRequest(data, "作业区域基本信息" + new Date().getTime());
    },
    // 方案信息pdf下载
    downloadProgramme () {
      if (this.result.selected) {
        const data = JSON.parse(JSON.stringify(this.result.selected));
        data.type = this.planType;
        this.downloadRequest(
          data,
          `${this.title}方案` + new Date().getTime()
        );
      }
    },
    // 上传成功
    handleUploadSuccess (res) {
      if (res.code === 200 && res.data) {
        if(res.data.flag === 1) {
          this.$message({
            message: "不是大地2000的坐标系",
            type: "warning"
          });
        }else{
          this.$emit("upLoadShpFile", res.data);
        }
      } else {
        this.$message({
          message: "解析失败",
          type: "warning"
        });
      }
    },
    // 上传前
    handleBeforeUpload (file) {
      if (
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.type === "application/vnd.ms-excel"
      ) {
        this.analysisExecl(file);
        return false;
      }
    },
    // 上传失败
    handleUploadError (res) {
      this.$message({
        message: "解析失败",
        type: "warning"
      });
    },
    // 解析execl
    analysisExecl (file) {
      const _this = this;
      const fileReader = new FileReader();
      fileReader.onload = function (ev) {
        try {
          var data = ev.target.result;
          var workbook = XLSX.read(data, {
            type: "binary"
          }); // 以二进制流方式读取得到整份excel表格对象
          var persons = []; // 存储获取到的数据
        } catch (e) {
          this.$message({
            message: "文件类型不正确",
            type: "warning"
          });
          return;
        }
        // 表格的表格范围，可用于判断表头是否数量是否正确
        var fromTo = "";
        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]["!ref"];
            persons = persons.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            );
            // break; // 如果只取第一张表，就取消注释这行
          }
        }
        // 格式化数据
        _this.formatLatLong(persons);
      };
      // 以二进制方式打开文件
      fileReader.readAsBinaryString(file);
    },
    // 格式化数据
    formatLatLong (latLong) {
      const reg = /^[EW]?((\d|[1-9]\d|1[0-7]\d)[°](\d|[0-5]\d)['](\d|[0-5]\d)(\.\d{1,2})?["]?$)/;
      try {
        const res = [];
        latLong.forEach(item => {
          // 判定坐标信息类型
          if (item.x && item.y && item.kid) {
            res.push(GeometryUtils.toPoint(item.x, item.y, item.kid));
          } else if (reg.test(item.x) && reg.test(item.y)) {
            const duX = item.x.split("°")[0];
            var fenX = item.x.split("°")[1].split("'")[0];
            var miaoX = item.x
              .split("°")[1]
              .split("'")[1]
              .split('"')[0];
            const duY = item.y.split("°")[0];
            var fenY = item.y.split("°")[1].split("'")[0];
            var miaoY = item.y
              .split("°")[1]
              .split("'")[1]
              .split('"')[0];
            res.push(
              GeometryUtils.toPoint(
                GeometryUtils.toDigital(
                  parseFloat(duX),
                  parseFloat(fenX),
                  parseFloat(miaoX)
                ),
                GeometryUtils.toDigital(
                  parseFloat(duY),
                  parseFloat(fenY),
                  parseFloat(miaoY)
                )
              )
            );
          } else if (typeof item.x === "number" && typeof item.y === "number") {
            res.push(GeometryUtils.toPoint(item.x, item.y));
          }
        });
        this.$emit("analysisExecl", res);
      } catch {
        this.$message({
          message: "文件中点位格式不正确",
          type: "warning"
        });
      }
    },
    // 新建按钮
    addHandle () {
      this.addTaskHidden = false;
      this.addForm = {
        name: "",
        description: "",
        ecoWorkTasks: [], //作业图形
        type:this.type
      }
    },
    // 选项卡回调
    tabClick () { },

    /**
     * 查询
     */
    async queryWorkTaskByName () {
      let param = {
        name: this.searchValue,
        type:this.type
      };
      let results = await queryWorkTaskByName(param);
      if (results) {
        this.tableData = results;
      }
    },

    // 确定新增
    onSubmit () {
      this.$refs.addForm.validateField("name",async (valid)=>{
        if(valid){
          return false
        }else{
          if(this.addForm.ecoWorkTasks && this.addForm.ecoWorkTasks.length > 0){
            let param = {
              name: this.addForm.name,
              description: this.addForm.description,
              type:this.type,
              ecoWorkTasks: this.addForm.ecoWorkTasks
            };
            let res = await addWorkTask(param);
            if (res.success) {
              this.addTaskHidden = true;
              this.searchValue = ""
              this.queryWorkTaskByName();
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              });
            }
          }else{
            this.$message({
              message: '请绘制区域或上传文件',
              type: 'warning'
            });
          }
        }
      })
    },
    /**
     * 定位
     */
    locationHandler (item) {
      if (item && item.hasOwnProperty("ecoWorkTasks") && item.ecoWorkTasks.length > 0) {
        this.$emit("locationHandler", item.ecoWorkTasks);
      }
    },
    /**
     * 删除
     */
    async deleteClickHandler (item) {
      let b = await delWorkTask(item);
      if (b) {
        this.queryWorkTaskByName();
      }
    },
    //接收图形信息
    acceptGraphic (geometries) {
      let owner = this;
      owner.addForm.ecoWorkTasks = [];
      if (geometries && geometries.length > 0) {
        geometries.forEach(geowkt => {
          let item = {
            geometry: geowkt
          };
          owner.addForm.ecoWorkTasks.push(item);
        });
      }
    }
  },
  mounted () {
    this.queryWorkTaskByName();
  }
};
</script>
<style lang="scss" scoped>
.eco-suitable-task-drawer {
  position: absolute;
  top: 100px;
  left: 0;
  z-index: 1;

  .eco-suitable-main {
    height: 56vh;
    padding: 0px 10px;
    background-color: #fff;
    overflow-x: hidden;
    overflow-y: auto;

    

    ::v-deep.el-tabs__item {
      font-size: 16px;
      color: #000;

      &:hover {
        color: #000;
      }
    }

    .draw-info {
      width: 100%;
      background-color: rgb(246, 246, 246);
      border: 1px solid rgb(222, 222, 222);
      border-radius: 5px;
      line-height: 30px;
      padding: 20px;
      color: rgb(112, 112, 112);
    }

    .draw-area-button-container {
      text-align: center;
      padding-top: 15px;

      .draw-btn {
        width: 150px;
      }
    }

    ::v-deep .el-tabs.el-tabs--top {
      width: 100%;
      height: 100%;
      .el-tabs__content {
        width: 100%;
        height: calc(100% - 55px);
        .el-tab-pane {
          height: 100%;
        }
      }
    }

    .project-task-root {
      width: 100%;
      height: 100%;
      .task-header {
        padding: 0 0 10px 0;
        position: relative;
        display: flex;
        flex-direction: row;
        align-items: center;

        .ipt {
          flex: 0.6;
          margin-right: 10px;
        }

        .search {
          flex-grow: 0;
        }

        .add {
          position: absolute;
          float: right;
          right: 10px;
        }
      }

      .task-content {
        height: calc(100% - 60px);
        overflow: auto;
        padding-right: 10px;
        &::-webkit-scrollbar {
          width: 8px;
          height: 8px;
        }
        /*定义滚动条轨道 内阴影+圆角*/
        &::-webkit-scrollbar-track {
          border-radius: 0;
          background-color: rgba(35, 31, 125, 0.6);
        }
        /*定义滑块 内阴影+圆角*/
        &::-webkit-scrollbar-thumb {
          border-radius: 4px;
          background-image: linear-gradient(90deg, #086b7a, rgb(17,81,30));
        }

        .task-item {
          margin-bottom: 12px;
          display: flex;
          justify-content: space-between;
          border: 1px solid rgba(0,0,0,.2);
          border-radius: 5px;
          padding: 0 24px;
          .left {
            min-width: 200px;
            p {
              margin: 10px 0;
              overflow: hidden;
              text-overflow:ellipsis;
              white-space: nowrap;
            }
            font-size: 14px;
          }
          .right {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          }
        }

        .empty-box {
          min-height: 300px;
          display:flex;
          justify-content: center;
          align-items: center;

          p {
            margin: 12px;
            color: rgba(0,0,0,.6);
          }
        }

        .delete-btn {
          color: #409eff;
          font-size: 12px;
          cursor: pointer;
          i {
            margin-right: 2px;
          }
        }
      }
    }

    .add-task-wrapper {
      width: 100%;
      height: 100%;
      overflow: auto;
      padding-right: 10px;

      &::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }
      /*定义滚动条轨道 内阴影+圆角*/
      &::-webkit-scrollbar-track {
        border-radius: 0;
        background-color: rgba(35, 31, 125, 0.6);
      }
      /*定义滑块 内阴影+圆角*/
      &::-webkit-scrollbar-thumb {
        border-radius: 4px;
        background-image: linear-gradient(90deg, #086b7a, rgb(17,81,30));
      }
    }
  }
}

.eco-suitable-area-drawer {
  position: absolute;
  top: 100px;
  right: 0;
  z-index: 1;

  .eco-suitable-main {
    height: 65vh;
    background-color: rgb(245, 243, 243);
    overflow-x: hidden;
    overflow-y: auto;

    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
    /*定义滚动条轨道 内阴影+圆角*/
    &::-webkit-scrollbar-track {
      border-radius: 0;
      background-color: rgba(35, 31, 125, 0.6);
    }
    /*定义滑块 内阴影+圆角*/
    &::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background-image: linear-gradient(90deg, #086b7a, rgb(17,81,30));
    }

    .header {
      position: relative;
      padding: 0 14px 10px 14px;
      font-size: 16px;
      color: #3e3e3e;
      &.border {
        border-top: 12px solid #fff;
      }

      & > div {
        margin-bottom: 6px;
        // white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;

        :last-child {
          margin-bottom: 0;
        }

        i {
          display: inline-block;
          width: 18px;
          height: 18px;
          margin-right: 6px;
          vertical-align: bottom;

          &.icon-location {
            background: url("~@/assets/images/location.png") no-repeat;
            background-size: cover;
          }

          &.icon-area {
            background: url("~@/assets/images/area.png") no-repeat;
            background-size: cover;
          }

          &.el-icon-s-flag {
            color: rgb(63, 129, 193);
          }

          &.icon-city {
            background: url("~@/assets/images/city.png") no-repeat;
            background-size: cover;
          }
        }
      }

      .lon-lat {
        display: flex;
        span {
          display: inline-block;
          width: 50%;
        }
      }
    }

    .guidance-plan {
      padding-left: 16px;
      .plan-body {
        padding: 10px 14px;

        .con {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;

          &:last-child {
            margin-bottom: 0;
          }

          h4,
          p,
          .score {
            background-color: #fff;
            border-radius: 5px;
            margin: 0;
            padding: 18px 14px;
            font-size: 14px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          h4 {
            font-weight: bold;
            color: red;
            font-size: 20px;
            margin: 0;
            width: 100px;
          }
          .score {
            margin-left: 6px;
            font-size: 20px;
            font-weight: bold;
            color: #f56c6c;
            width: 110px;
          }
          p {
            flex: 1;
            margin-left: 6px;
            span {
              height: fit-content;
              display: -webkit-box;
              word-break: break-all;
              -webkit-box-orient: vertical;
              -webkit-box-pack: center;
              overflow: hidden;
              text-overflow: ellipsis;
              -webkit-line-clamp: 4;
              overflow: hidden;
            }
          }
        }
      }
    }

    .tit {
      display: flex;
      height: 40px;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0 !important;

      h3 {
        font-weight: normal;
        color: #000;
        margin: 0;
      }
      .el-button {
        height: 30px;
      }
      .icon-download {
        width: 20px;
        height: 20px;
        background: url("~@/assets/images/download-blue.svg") no-repeat;
        background-size: cover;
        cursor: pointer;
      }
    }

    .add-task {
      padding: 20px 14px;

      .el-upload__tip .execl {
        color: deepskyblue;
      }
    }
  }
}
</style>